package org.iartisan.wechatsdk.mp.material

import org.iartisan.runtime.env.EnvContextConfig
import org.iartisan.runtime.utils.HttpRequestUtil
import org.iartisan.wechatsdk.Utils._
import org.iartisan.wechatsdk.common.{Constant, GlobalCache}
import org.iartisan.wechatsdk.mp.material.res.{BatchgetMaterialRes, MaterialcountRes}
import org.iartisan.wechatsdk.{JAccessToken, LogAspect}

import scala.collection.JavaConverters._
import scala.collection.mutable._

/**
  * 微信素材服务
  *
  * @author King  2019/5/29
  */
object WechatMaterialService extends LogAspect {

  private val GET_MATERIALCOUNT_URL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=%s"
  private val BATCHGET_MATERIAL_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s"

  def getAccessToken() = {
    val appId = EnvContextConfig.get(Constant.wechat_mp_appid)
    var accessToken = GlobalCache.getAccessToken(appId)
    if (null == accessToken) {
      val secret = EnvContextConfig.get(Constant.wechat_mp_secret)
      accessToken = JAccessToken.getAccessToken(appId, secret)
    }
    accessToken
  }

  def batchgetMaterialNews(_type: String, offset: Int, count: Int) = {
    log.info(s"===>开始获取素材 offset:$offset,count:$count")
    val reqUrl = String.format(BATCHGET_MATERIAL_URL, getAccessToken)
    val params = Map("type" -> _type, "offset" -> offset, "count" -> count).asJava
    val res = HttpRequestUtil.sendPost(reqUrl, params.toJson).body.string
    //隐式转换
    res.toObject[BatchgetMaterialRes]
  }

  /**
    * 获取素材数量
    *
    * @return
    */
  def getMaterialcount = {
    log.info(s"===>开始获取素材总数公众号 ")
    val reqUrl = String.format(GET_MATERIALCOUNT_URL, getAccessToken)
    val res = HttpRequestUtil.sendGet(reqUrl)
    //隐式转换
    res.toObject[MaterialcountRes]
  }

}
